/*
 * pwm.c
 *
 *  Created on: 2015-03-08
 *      Author: root
 */

#include "pwm.h"
#include "uart.h"
#include "definitions.h"


int _frequency = 0;
int _period = 0;
int _duty = 0;
int _onOff = 0;
//int _PWM = 0x04;

/*
void initPWM(int freq)
{
	ROM_GPIOPinConfigure(GPIO_PF0_T0CCP0);
	ROM_GPIOPinTypeTimer(GPIO_PORTF_BASE, PF_0);

	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
	ROM_TimerConfigure(TIMER5_BASE, TIMER_CFG_SPLIT_PAIR|TIMER_CFG_A_PWM);

	_period = (ROM_SysCtlClockGet() / freq);

	ROM_TimerLoadSet(TIMER5_BASE, TIMER_A, _period-_duty-1);
	ROM_TimerMatchSet(TIMER5_BASE, TIMER_A, _duty);

	ROM_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
	ROM_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
	ROM_IntEnable(INT_TIMER5A);
	ROM_TimerEnable(TIMER5_BASE, TIMER_A);

	bt_UARTsend("pwm initialized\r\n");

}
*/
void initPWM(int freq)
{
	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
	//set timer period: 40MHz/10/2 = 2MHz = 0.5us
	//for 1000us = 1ms use Div by 0.1 and then 4, 40MHz / 0.1 / 4 = 1ms
	//ROM_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
	ROM_TimerConfigure(TIMER5_BASE, TIMER_CFG_A_PWM);

	_period = ROM_SysCtlClockGet()/freq;		//for 1s
	ROM_TimerLoadSet(TIMER5_BASE, TIMER_A, _period-1);

	//Timer interrupt setup
	ROM_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
	ROM_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
	ROM_TimerControlEvent(TIMER5_BASE, TIMER_A, TIMER_TIMA_TIMEOUT);
	ROM_IntEnable(INT_TIMER5A);
	ROM_TimerEnable(TIMER5_BASE, TIMER_A);
	bt_UARTsend("Timer5 Loaded\r\n");

}

void pwmHandler(void)
{
	//FIXME
	//set _onOff ^= PWM where PWM is macro

	_onOff ^= _PWM;	//Currently for PA_2

	//first run, time = duty, second run, time = period - duty
	(_onOff) ? ROM_TimerLoadSet(TIMER5_BASE, TIMER_A, _duty) : ROM_TimerLoadSet(TIMER5_BASE, TIMER_A, _period-_duty);

	//write out state
	ROM_GPIOPinWrite(GPIO_PORTF_BASE, _PWM, _onOff);

	//clear interrupts
	ROM_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
	//bt_UARTsend("pwm fire\r\n");
}

void pwmSetDuty(int duty_cycle)
{
	if(duty_cycle > 1000)
	{
		duty_cycle = 1000;
	}
	duty_cycle = duty_cycle*_period;
	_duty = duty_cycle/1000;
}
